package com.oxy.filter;

import java.io.IOException;
import java.util.Enumeration;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;

import com.oxy.common.constant.SecurityConstant;
import com.oxy.security.AccessGrantor;
import com.oxy.security.UserInfo;
import com.oxy.util.Oxy;

public class SecurityFilter implements Filter {
	private final static Log logger = Oxy.getLogManager().getLogAccess();
	
	public void destroy() {
		// TODO Auto-generated method stub

	}

	public void doFilter(ServletRequest req, ServletResponse rsp, FilterChain filterChain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		HttpServletRequest httpReq = (HttpServletRequest) req;
		HttpSession httpSess = httpReq.getSession();
		HttpServletResponse httpRsp = (HttpServletResponse) rsp;

		// log the request
		StringBuffer sb = new StringBuffer();
		String remoteAddr = httpReq.getRemoteAddr()+":"+httpReq.getRemotePort();
		sb.append("Request from ["+remoteAddr+"], ");
		sb.append("sid="+httpReq.getRequestedSessionId()+", ");
		sb.append("url="+httpReq.getRequestURL());
		
		if(logger.isDebugEnabled()){
			Enumeration<String> enu = httpReq.getParameterNames();
			sb.append(", param=[");
			while(enu.hasMoreElements()){
				String key = enu.nextElement();
				sb.append(key+"="+httpReq.getParameter(key));
				if(enu.hasMoreElements()){
					sb.append(", ");
				}
			}
			sb.append("]");
		}
		logger.debug(sb.toString());
		
		boolean isValidAccess = true;
		String userName = null;
		UserInfo user = (UserInfo)httpSess.getAttribute(SecurityConstant.AUTH.CURRENT_USER);
		String res = httpReq.getRequestURI();
		if(user == null){
			userName = "visitor";
			isValidAccess = AccessGrantor.isResAccessableForFree(res);
		}
		else{
			userName = user.getUserName();
			isValidAccess = AccessGrantor.isResAccessableForUser(userName, res);
		}
		
		if(isValidAccess == false){
			logger.info("Invalid access: "+httpReq.getRequestURI()+" from ["+remoteAddr+"] by ["+userName+"]");
			//httpRsp.sendRedirect(SysCfgLoader.getProperty(SysConstant.URL.URL_ROOT)+"/"+"");
		}
		
//		boolean isFolder = false;
//		if (reqUrl.endsWith(".js")) {
//			int i=reqUrl.lastIndexOf('/');
//			String miscName = reqUrl.substring(i+1, reqUrl.length()-3);
//			String[] arr=miscName.split("_");
//			if(arr.length==3){
//				String modName=arr[0];
//				String actName=arr[1];
//				String elemName=arr[2];
//				String dispatchUrl = "/misc/getjs.html?mod="+modName+"&act="+actName+"&paraIn.elem="+elemName;
//				httpRsp.sendRedirect(dispatchUrl);
//			}
//		}
		filterChain.doFilter(req, rsp);
	}

	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub
	}
}
